﻿/*!
*   versão: 1.2
*
*   $(" ").modal(show|hide)
*   ----------------------------------------------------------------------------------
*   Opções
*       show: mostra o elemento em uma modal;
*       hide: oculta o elemento
*   
*   Descrição
*       O elemento que será exibido deverá ter definido o width e o height
*
*
*   $(" ").numero()
*   ----------------------------------------------------------------------------------
*   Descrição
*       O elemento para a aceitar a digitação das seguintes teclas:
*         · números de 0 a 9; Setas; delete; home; end; backspace; shift; 
*           tab; ctrl + a; ctrl + c; ctrl + x; ctrl + v.
*
*   $.dom(elemento, [html], [valor])
*   ----------------------------------------------------------------------------------
*   Descrição
*       Cria um novo elemento DOM do cache
*       Tipos aceitos: div; h4, p; ul; li; span; a; option; table; tr; td;
*       Exemplos:
*           $.dom("a", "clique aqui", "http://www.jquery.com");
*           $.dom("option", "São paulo", "1");
*           $.dom("h4", "Hoje");
*           $.dom("ul", $.dom("li", "para listas"));
*
*/
(function ($) {
    var dom = {
        $cache: {
            "div": $("<div />"),
            "h4": $("<h4 />"),
            "p": $("<p />"),
            "ul": $("<ul />"),
            "li": $("<li />"),
            "span": $("<span />"),
            "a": $("<a />"),
            "option": $("<option />"),
            "table": $("<table />"),
            "tr": $("<tr />"),
            "td": $("<td />")
        },
        x: function (e, h) {
            h = (typeof (h) == "object") ? h : $.trim(h);
            return this.$cache[e].clone().html(h);
        },
        criar: function (e, h, v) {
            var _$dom = this.x(e, h);
            if (e == "a")
                return _$dom.attr("href", v || "javascript:void(0);");
            else if (e == "option")
                return _$dom.attr("value", v);
            else
                return _$dom;
        }
    };

    $.dom = function (elemento, html, valor) {
        return dom.criar($.trim(elemento).toLowerCase(), html, valor);
    }

    // funções para auxiliar as modais
    function indexMaior() {
        var maxIndex = 1000;
        $("body *").each(function (idx, elem) {
            var zIdx = $.trim($(elem).css("z-index"));
            zIdx = zIdx != "" ? zIdx == "auto" ? 0 : zIdx : 0;
            maxIndex = Math.max(parseInt(zIdx, 10), parseInt(maxIndex, 10)) + 1;
        });
        return maxIndex;
    }

    function posicaoCentro(altura, largura) {
        var t = (-(altura / 2)) + $(document).scrollTop();
        var l = -(largura / 2);
        return { zIndex: indexMaior(), marginLeft: l, marginTop: t };
    }

    function newOverlay() {
        return dom.criar("div")
                .addClass("overlay-modal")
                .width($(document).width())
                .height($(document).height())
                .css("z-index", indexMaior());
    }

    function newAlert(tipo) {
        var $body = $("body"),
            tamW = 350,
            tamH = 170,
            css = posicaoCentro(tamH, tamW),
            $overlay = newOverlay();

        css.marginTop = css.marginTop + ($(".alert-modal").length * 20);
        css.marginLeft = css.marginLeft + ($(".alert-modal").length * 20);

        var tpAlert = {
            "erro": "alert-modal-erro",
            "info": "alert-modal-info",
            "sucesso": "alert-modal-sucesso",
            "confirm": "alert-modal-confirm"
        };
        var tipoAlert = tpAlert[tipo] != undefined ? tpAlert[tipo] : "alert-modal-erro";

        var $alert = dom.criar("div");
        var $titulo = dom.criar("div", "<span>Atenção!</span>").addClass("alert-modal-titulo");
        var $texto = dom.criar("div").addClass("alert-modal-texto");
        var $botoes = dom.criar("div").addClass("alert-modal-botoes");

        var fnRemove = function () {
            $alert.animate({ top: -tamW }, function () {
                $alert.remove();
                $overlay.remove();
                return this;
            });
        };
        var fnShow = function () {
            $alert.animate({ "margin-top": css.marginTop });
        };

        $alert
            .html($titulo)
            .append($texto)
            .append($botoes)
            .width(tamW)
            .height(tamH)
            .addClass("alert-modal modal " + tipoAlert)
            .css("margin-left", css.marginLeft)
            .css("margin-top", -(tamH * 2))
            .css("z-index", css.zIndex)
            .bind("remove", fnRemove)
            .bind("showAlert", fnShow);

        $body.append($overlay).append($alert);
        return $alert;
    }
    // Ok Revisado
    jQuery.fn.modal = function (opt) {

        var maxIndex = 1000;

        jQuery("body *").each(function (idx, elem) {
            var zIdx = ($(elem).css("z-index") == "auto") ? 0 : $(elem).css("z-index");
            if (zIdx) maxIndex = Math.max(zIdx, maxIndex) + 1;
        });

        var tamH = this.height(),
            tamW = this.width(),
            pTop = (($(window).height() - tamH) / 2),
            pLeft = (($(window).width() - tamW) / 2);

        var _this = this;
        var css = { "z-index": maxIndex, "position": "absolute", top: pTop, left: pLeft };

        var mostrar = function () {
            if ($(".Modal_76253").length == 0)
                $("body").append(jQuery("<div/>").addClass("overlay-modal Modal_76253"));

            $("body").append(_this.css(css).show());
            $(".Modal_76253").css("z-index", maxIndex).show();
        };

        var fechar = function () {
            $(".Modal_76253").hide();
            _this.hide();
        };

        switch (jQuery.trim(opt).toLowerCase()) {
            case "show": mostrar(); break;
            case "hide": fechar(); break;
        }
        return _this;
    }; /*
    $.fn.modal = function(opt) {
        var $body = $("body"), _this = this;
        var css = posicaoCentro(this.height(), this.width());
        var $overlay = newOverlay().addClass("modal_76253");

        var mostrar = function() {
            if (!$(".modal_76253").length) $body.append($overlay);

            $body.append(_this.css(css).show());
            $(".modal_76253").show();
        };

        var fechar = function() {
            $(".modal_76253").hide(); _this.hide();
        };

        switch ($.trim(opt).toLowerCase()) {
            case "show": mostrar(); break;
            case "hide": fechar(); break;
        }
        return this;
    };
*/

    // revisado OK
    $.alert = function (msg, tipo, callback) {

        var $body = $("body"),
            $alert = newAlert(tipo);

        var fnClick = function () {
            $alert.trigger("remove");
            if (typeof (tipo) == "function") tipo();
            else if (typeof (callback) == "function") callback();
        };

        var $btnOk = dom.criar("div")
            .html(dom.criar("span", dom.criar("a", "OK")))
            .addClass("alert-modal-btn")
            .click(fnClick);

        $alert
            .find(".alert-modal-botoes")
            .html($btnOk)
            .end()
            .find(".alert-modal-texto")
            .html(msg)
            .end()
            .show();

        return $alert.trigger("showAlert");
    };

    $.confirm = function (obj, cb, noCb) {
        var _obj = { msg: "-", titulo: "Atenção", callback: $.noop, noCallback: $.noop };
        var $alert = newAlert("confirm");
        if (typeof (obj) == "string") {
            _obj.msg = obj;
            if (typeof (cb) == "function") _obj.callback = cb;
            if (typeof (noCb) == "function") _obj.noCallback = noCb;
        } else {
            $.extend(_obj, obj);
        }

        var fnClick = function (tipo) {
            $alert.trigger("remove");
            var fn = $.noop;
            switch (tipo) {
                case "sim": fn = _obj.callback;
                    break;
                case "nao": fn = _obj.noCallback;
                    break;
            }
            if (typeof (fn) == "function") fn();
        };

        var $btnOk = dom.criar("div").addClass("alert-modal-btn");
        var $btnCa = dom.criar("div").addClass("alert-modal-btn");
        var $span = dom.criar("span", dom.criar("a"));

        $btnOk
            .html($span.clone().find("a").html("sim").end())
            .click(function () { fnClick("sim"); });

        $btnCa
            .html($span.clone().find("a").html("não").end())
            .click(function () { fnClick("nao"); });

        $alert
            .find(".alert-modal-botoes")
            .html($btnCa)
            .append($btnOk)
            .end()
            .find(".alert-modal-texto")
            .html(_obj.msg)
            .end()
            .show();

        return $alert.trigger("showAlert");
    };

    $.fn.numero = function () {
        var validaNumerico = function (e) {
            var tecla = e ? (e.keyCode ? e.keyCode : (e.which ? e.which : e.charCode)) : null;
            return (/^(48|49|50|51|52|53|54|55|56|57|8|9|46|16|35|36|37|38|39|40)$/g).test($.trim(tecla));
        }
        this.live("keypress", validaNumerico);
    };
})(jQuery);
window.alert = $.alert;
window.confirm = $.confirm;

/* Fim do plugin UNIP */

var master = new (function ($) {

    var $_site,
        $_menu,
        $_ctdo,
        _serverPath,
        _requisicoes;

    // seta o local onde está rodando o servidor
    this.serverPath = function (valor) {
        if (valor == undefined) return _serverPath;
        else _serverPath = ($.trim(valor));
        _serverPath = _serverPath.replace(/^\/$/gi, "");
    };

    function configDatePiker() {
        // só funciona se o jQuery UI estiver incluso
        if ($.isFunction($.fn.datepicker)) {
            $(".calendario").datepicker({
                altFormat: "dd-mm-yy",
                dateFormat: "dd/mm/yy",
                nextText: "Próximo",
                prevText: "Anterior",
                dayNamesMin: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"],
                dayNames: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"],
                monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
            });
        }
    }
    function configuraAjax() {
        var $modal = $("#mdal-ajax");

        $.ajaxSetup({
            type: "POST",
            cache: false,
            global: true,
            statusCode: {
                401: function () { window.location.reload(); },
                404: function () { alert('Página não encontrada'); },
                500: function (xml) {
                    try {
                        var message = (eval('(' + xml.responseText + ')')).ErrorMessage;

                        alert(message);
                        if (message == "Sessão expirada!")
                            window.location.reload();
                    }
                    catch (ex) { alert("Erro na conversão do JSON.") }
                }
            }
        });

        // configuração da modal
        _requisicoes = 0;
        $modal
            .bind("ajaxSend", function () {
                _requisicoes++; if (_requisicoes == 1) $(this).modal("show");
            })
            .bind("ajaxComplete", function () {
                _requisicoes--; if (_requisicoes == 0) $(this).modal("hide");
            });
    }

    function focusInputs() {
        $("input, select").live("focusin focusout", function (ev) {
            try {
                var $tgt = $(this).removeClass("input-focus");
                var lblFor = $tgt.attr("name") || $tgt.attr("id") || "";
                var $lbl = $("label[for=" + lblFor + "]").removeClass("label-focus");

                if (ev.type == "focusin") {
                    $tgt.addClass("input-focus");
                    $lbl.addClass("label-focus");
                }
            } catch (ex) { }
        });
    }
    /*
    this.logout = function () {
    var callBk = function (json) {
    if (json.d) window.location = _serverPath + "/Default.aspx";
    else alert("Erro ao efetuar o logout", "erro");
    };
    $.post(_serverPath + "/Default.aspx/Logout", callBk);
    }*/

    // função que oculta o menu
    this.escondeMenu = function (ev) {
        var $ev = $(ev.currentTarget),
            oculto = $_site.hasClass("menu-oculto");
        var mostraBt = function () {
            $ev.html(oculto ? "Esconder menu" : "Mostrar menu")
              .animate({ width: "100px" }, "fast");
        };
        if (oculto) {
            $ev.animate({ width: 0 }, function () {
                mostraBt();
                $_ctdo.animate({ width: "80%" });
                $_menu.animate({ width: "18%" }, function () {
                    $_site.removeClass("menu-oculto");
                });
            });
        }
        else {
            $ev.animate({ width: 0 }, function () {
                mostraBt();
                $_ctdo.animate({ width: "98%" });
                $_menu.animate({ width: 0 }, function () {
                    $_site.addClass("menu-oculto");
                });
            });
        }
    };

    // função para o clik no li do menu
    this.goTo = function (ev) {
        var $a = $(this).find("a");
        if ($a.length != 0) {
            var lk = $a.attr("href") || "";
            if (lk != "") window.location = lk;
        }
    };

    // função de inicio da pagina
    this.inicio = function () {
        $_menu = $("#st-cent-navg");
        $_ctdo = $("#st-cent-ctdo");
        $_site = $("#st");
        $(".numero").numero();
        configDatePiker();
        configuraAjax();
        focusInputs();
    };

})(jQuery);


var hash = {
    getHash: function (variavel) {
        var h = (($.trim(window.location.hash) != "") ? $.trim(window.location.hash).replace(/^(#)/gi, "") : "");
        h = $.grep(((h != "") ? h.split("/") : [""]), function (elem) { return elem.split("!")[0] == variavel });
        if (h.length == 0) return ""; else return (h[0].split("!").length > 1) ? h[0].split("!")[1] : "";
    },
    setHash: function (variavel, value) {
        var nv = "/" + variavel + "!" + value;
        var va = $.trim(this.getHash(variavel));
        var h = (($.trim(window.location.hash) != "") ? $.trim(window.location.hash).replace(/^(#)/gi, "") : "");
        if (va == "" && value != null) window.location.hash = h + nv;
        else window.location.hash = h.replace("/" + variavel + "!" + va, (value == null) ? "" : nv);
        return value;
    },
    getCampanha: function () {
        return this.getHash("cam");
    },
    setCampanha: function (val) {
        return this.setHash("cam", val);
    },
    getSistema: function () {
        return this.getHash("sis");
    },
    setSistema: function (val) {
        return this.setHash("sis", val);
    },
    getTurma: function () {
        return this.getHash("tur");
    },
    setTurma: function (val) {
        return this.setHash("tur", val);
    },
    getDisciplina: function () {
        return this.getHash("dis");
    },
    setDisciplina: function (val) {
        return this.setHash("dis", val);
    }
};


$(function () {
    master.serverPath($("#appPath").val());
    master.inicio();
    //$(".esconde-menu").click(master.escondeMenu);
    //$(".logout").click(master.logout);
    $("#st-cent-navg ul li").click(master.goTo);

    $("form").makeValidationInline();
});